package com.epam.facebook_client;

import java.util.HashMap;
import java.util.Map;

import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.epam.facebook_client.api.API;
import com.epam.facebook_client.content.contract.AppContract;
import com.epam.facebook_client.manager.ImageManager;
import com.epam.facebook_client.processor.FeedsProcessor;
import common.adapters.AbstractCursorAdapter;
import common.processor.IProcessor;

public class ListFeedActivity extends BaseServiceActivity implements LoaderCallbacks<Cursor> {

	public static final String FEED_ID = "id";

	private static final int LOAD_FEEDS = 0;
	private static final String TAG = ListFeedActivity.class.getSimpleName();
	private ListView listView;
	private ProgressBar progressBarCenter;
	private AbstractCursorAdapter adapter;
	private ImageManager imageManager;
	private String nextPageUrl;
	private Map<String, String> parameter;

	private RelativeLayout loadingBottomLayout;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_list_feeds);
		listView = (ListView) findViewById(R.id.listFeed);
		progressBarCenter = (ProgressBar) findViewById(R.id.progressBar);
		loadingBottomLayout = (RelativeLayout) findViewById(R.id.loadingBottom);
		imageManager = ImageManager.get(this);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
				Intent i = new Intent(getApplicationContext(), FeedActivity.class);
				i.putExtra(FEED_ID, id);
				startActivity(i);
			}
		});

		listView.setOnScrollListener(new OnScrollListener() {

			

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
					int totalItemCount) {
				if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
					if (!TextUtils.isEmpty(nextPageUrl)) {
						parameter = new HashMap<String, String>(2);
						parameter.put(FeedsProcessor.EXTRA_URL, nextPageUrl);
						parameter.put(IProcessor.EXTRA_EXECUTE_METHOD, IProcessor.METHOD_GET);
						startServiceHelper(parameter, loadingBottomLayout, FeedsProcessor.ACTION);
					}
				}
			}
		});
		parameter = new HashMap<String, String>(2);
		parameter.put(FeedsProcessor.EXTRA_URL, API.FEED_GET);
		parameter.put(IProcessor.EXTRA_EXECUTE_METHOD, IProcessor.METHOD_GET);
		startServiceHelper(parameter, loadingBottomLayout, FeedsProcessor.ACTION);
	}

	@Override
	protected void onStart() {
		super.onStart();
		getSupportLoaderManager().initLoader(LOAD_FEEDS, null, this);
	}

	@Override
	public void onServiceResult(int requestId, Intent requestIntent, int resultCode, Bundle resultData) {
		loadingBottomLayout.setVisibility(View.GONE);
		switch (resultCode) {
		case IProcessor.RESULT_OK:
			nextPageUrl = resultData.getString(IProcessor.EXTRA_URL);
			break;
		case IProcessor.RESULT_ERROR:
			Exception e = (Exception) resultData.getSerializable(IProcessor.EXTRAS_ERROR);
			Log.e(TAG, "ERROR: " + e);
			Toast.makeText(this, "ERROR: " + e.getMessage(), Toast.LENGTH_SHORT).show();
			break;
		}
	}

	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle bundle) {
		progressBarCenter.setVisibility(View.VISIBLE);
		String[] projection = { AppContract.FeedColumns.FEED_ID, AppContract.FeedColumns.NAME,
				AppContract.FeedColumns.TYPE, AppContract.FeedColumns.STORY, AppContract.FeedColumns.PICTURE,
				AppContract.FeedColumns._ID };
		return new CursorLoader(this, AppContract.FeedColumns.CONTENT_URI, projection, null, null,
				AppContract.FeedColumns.SORT_ORDER_DEFAULT);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		progressBarCenter.setVisibility(View.GONE);
		if (cursor.getCount() > 0) {
			int currentPosition = listView.getFirstVisiblePosition();
			View view = listView.getChildAt(0);
			int top = (view == null) ? 0 : view.getTop();
			String[] columnNames = { AppContract.FeedColumns.NAME, AppContract.FeedColumns.TYPE,
					AppContract.FeedColumns.STORY, AppContract.FeedColumns.PICTURE };
			int[] viewId = { R.id.feedUser, R.id.feedType, R.id.feedStory, R.id.feedImage };
			adapter = new AbstractCursorAdapter(this, cursor, imageManager, viewId, columnNames) {

				@Override
				public int getLayoutAdapterId() {
					return R.layout.adapter_feed_list_item;
				}

				@Override
				public void setImageNull(ImageView imageView) {
					imageView.setVisibility(View.GONE);
				}

			};
			listView.setAdapter(adapter);
			listView.setSelectionFromTop(currentPosition, top);
		}
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_feeds, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_refresh:

			break;
		case R.id.menu_add_post:
			startActivity(new Intent(this, PostStatusActivity.class));
			break;
		case R.id.menu_clear:
			parameter = new HashMap<String, String>(2);
			parameter.put(FeedsProcessor.EXTRA_URL, API.FEED_GET);
			parameter.put(IProcessor.EXTRA_EXECUTE_METHOD, IProcessor.METHOD_DELETE);
			startServiceHelper(parameter, loadingBottomLayout, FeedsProcessor.ACTION);
			break;
		default:
			break;
		}
		return super.onMenuItemSelected(featureId, item);
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		getSupportLoaderManager().initLoader(LOAD_FEEDS, null, this);
		super.onConfigurationChanged(newConfig);
	}
}
